import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Form, Card, Input, Select, Icon, Button, message, Switch, TreeSelect } from "antd";
import { generateAuthPassword } from '../../../utils/request';


const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const TreeNode = TreeSelect.TreeNode;

function fn(data, pid) {
  let result = [], temp;
  if(data && pid) {
    for (let i in data) {
      if (data[i].parentId == pid) {
        result.push(data[i]);
        temp = fn(data, data[i].deptId);
        if (temp.length > 0) {
          data[i].children = temp;
        }
      }
    }
  }
  return result;
}

Array.prototype.ToTreeJson = function (pid) {
  let result = [], temp;
  for (let i in this) {
    if (this[i].parentId == pid) {
      result.push(this[i]);
      temp = fn(this, this[i].deptId);
      if (temp.length > 0) {
        this[i].children = temp;
      }
    }
  }
  return result;
}

const treeDataFun = data =>{
  return data.map(item=>{
    if(item.children){
      return {children:treeDataFun(item.children),key:`${item.deptId}`,value:`${item.deptId}`, title:item.deptName};
    }else{
      return {key:`${item.deptId}`,value:`${item.deptId}`, title:item.deptName};
    }
  })
}


@connect(({ user, department, global }) => ({
  loading:user.loading,
  detaildata:user.detaildata,
  roleListSelect:user.roleListSelect,
  selectSource:global.selectSource,
  resdata: department.resdata,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class NoticeAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.detailInfoId = this.props.match.params.id && this.props.match.params.id!='detail' ? this.props.match.params.id : 0;
    this.state={
      userType:"01",
    }
  }

  componentDidMount() {
    const { dispatch,form } = this.props;

    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });

    // 获取部门列表
    dispatch({
      type: 'department/fetch_department_list',
    });


    // 获取角色下拉列表
    dispatch({
      type: "user/fetch_role_nopage",
    })

    form.setFieldsValue({
      username:undefined,
      password:undefined,
    });

    if (this.detailInfoId!==0) {
        // 编辑时 读取详情
        dispatch({
          type: "user/fetch_user_info",
          payload: {
            userId: this.detailInfoId
          }
        }).then(()=>{
          this.setState({userType:this.props.detaildata.userType})
        })
    }

  }




  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        const action = this.detailInfoId!=0 ? 'edit' : 'add';
        const userId = this.detailInfoId!=0 ? this.detailInfoId : undefined;

        if(values.password){
          values.password = generateAuthPassword(values.password);
        }

        if(values.roleIdList && !(values.roleIdList instanceof Array)){
          values.roleIdList=[values.roleIdList];
        }

        if(values.user_name){
          values.username=values.user_name;
          values.user_name=undefined;
        }
        if(values.pass_word){
          values.password=values.pass_word;
          values.pass_word=undefined;
        }

        values.status=values.status ? 0 : 1;


        // if(values.taskTime){
        //   values.beginTime = values.taskTime[0].unix() * 1000;
        //   values.endTime = values.taskTime[1].unix() * 1000;
        // }

        dispatch({
          type: `user/${action}_user`,
          payload: {
            ...values,
            userId
          }
        }).then(() => {
            this.handleReset();
            message.success(this.detailInfoId!=0 ? "用户信息已修改" : "用户已添加");
            if(this.detailInfoId!=0){
              this.goBack();
            }
        });
      }
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  };


  goBack = () => {
    const { dispatch, location } = this.props;
    router.push({ pathname:`/system/users/list`,  query: { ...location.query} });
  }

  handleChangeUserType =(value, option) =>{
    const { form } = this.props;
    this.setState({
      userType:value,
    },()=>{
      form.setFieldsValue({
        deptId:undefined,
      });
    })
  }



  render() {
    const { loading, resdata, detaildata, roleListSelect, selectSource } = this.props;
    const { userType } = this.state;
    const { getFieldDecorator } = this.props.form;

    const treeData=treeDataFun(resdata.list.ToTreeJson(0));


    return (
       <Card
             bodyStyle={{padding:'50px 100px'}}
       >
            <Form layout="horizontal">
              <Row gutter={24}>
                <Col span={8}>
                  <FormItem label="真实姓名">
                    {getFieldDecorator("realName", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata.realName,
                      rules: [
                        {
                          required: true,
                          message: "请输入真实姓名"
                        }
                      ]
                    })(<Input placeholder="请输入真实姓名" />)}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="用户名">
                    {getFieldDecorator("user_name", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata.username,
                      rules: [
                        {
                          required: true,
                          message: "请输入用户名"
                        }
                      ]
                    })(<Input placeholder="请输入用户名" type="text"    />)}
                  </FormItem>
                </Col>

                {this.detailInfoId==0 && (
                  <Col span={6}>
                    <FormItem label="密码">
                      {getFieldDecorator("pass_word", {
                        rules: [
                          {
                            required: true,
                            min: 8,
                            max: 16,
                            pattern: /^(?![^a-zA-Z]+$)(?!\D+$).{8,15}$/,
                            message: "请输入 8-16位，必须包含数字和字母 的新密码"
                          }
                        ]
                      })(<Input placeholder="8-16位，必须包含数字和字母" type="text"  autoComplete="off" />)}
                    </FormItem>
                  </Col>
                )}


                <Col span={8}>
                  <FormItem label="手机号">
                    {getFieldDecorator("mobile", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata.mobile,
                      rules: [
                        {
                          // required: true,
                          pattern: /^1\d{10}$/,
                          message: "手机号格式不正确"
                        }
                      ]
                    })(
                      <Input

                        placeholder="请输入手机号"
                      />
                    )}
                  </FormItem>
                </Col>


                <Col span={8}>
                  <FormItem label="邮箱">
                    {getFieldDecorator("email", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata.email,
                      rules: [
                        {
                          type: "email",
                          message: "输入的E-mail格式不正确"
                        },
                        {
                          message: "请输入你的E-mail!"
                        }
                      ]
                    })(<Input placeholder="请输入电子邮箱" />)}
                  </FormItem>
                </Col>



                <Col span={8}>
                  <FormItem
                    label="角色"
                  >
                    {getFieldDecorator('roleIdList', {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata.roleIdList,
                      rules: [{
                        required: true,
                        message: '请选择用户角色',
                      }],
                    })(
                      <Select
                        placeholder="请选择用户角色"
                      >
                        {
                          roleListSelect && roleListSelect.map(item => {
                            return <Option key={item.roleId} value={item.roleId}>{item.roleName}</Option>
                          })
                        }
                      </Select>
                    )}
                  </FormItem>
                </Col>


                <Col span={8}>
                  <FormItem
                    label="用户类型"
                  >
                    {getFieldDecorator('userType', {
                      initialValue: this.detailInfoId === 0 ? "01" : detaildata.userType,
                      rules: [{
                        required: true,
                        message: '请选择用户类型',
                      }],
                    })(
                      <Select
                        placeholder="请选择用户类型"
                        onSelect={this.handleChangeUserType}
                      >
                        <Option key={"01"} value={"01"}>甲方单位</Option>
                        <Option key={"02"} value={"02"}>维保单位</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                {
                  userType === "01" &&
                  <Col span={8}>
                    <FormItem label="部门">
                      {getFieldDecorator("deptId", {
                        initialValue:this.detailInfoId === 0 ? undefined : String(detaildata.deptId),
                        rules: [
                          { required: true, message: "请选择所在部门" },
                        ]
                      })(
                        <TreeSelect
                          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                          treeData={treeData}
                          allowClear={true}
                          placeholder="请选择所在部门"
                          treeDefaultExpandAll
                        />
                      )}
                    </FormItem>
                  </Col>
                }


                {
                  userType==="02" &&
                  <Col span={8}>
                    <FormItem label="维保单位" >
                      {getFieldDecorator("deptId", {
                        initialValue: this.detailInfoId === 0 ? undefined : (detaildata.deptId && detaildata.deptId),
                        rules: [
                          { required: true, message: "请选择维保单位" },
                        ]
                      })(
                        <Select placeholder="请选择维保单位"
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                                style={{ width: '100%' }}>
                          {selectSource.maintenance && selectSource.maintenance.map(item => (
                            <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                }


                <Col span={8}>
                  <FormItem label="是否禁用" colon={false}>
                    {getFieldDecorator("status", {
                      initialValue: this.detailInfoId === 0 ? undefined : !Boolean(Number(detaildata.status)),
                      valuePropName: 'checked',
                      rules: [
                        // { required: true, message: "请输入设备名称" },
                      ]
                    })(
                      <Switch  />
                    )}
                  </FormItem>
                </Col>

              </Row>



              <Row gutter={24} >
                <Col span={24} style={{textAlign:'center',padding:30}}>
                    <Button
                      onClick={this.handleFormSubmit.bind(this)}
                      type="primary"
                      size="large"
                      style={{marginRight:15}}
                      loading={loading.add}
                    >
                      提交
                    </Button>
                    <Button
                      onClick={this.handleReset.bind(this)}
                      type="default"
                      size="large"
                    >
                      重置
                    </Button>
                </Col>
              </Row>
            </Form>



       </Card>
    );
  }
}
